// Physical memory allocator, for user processes,
// kernel stacks, page-table pages,
// and pipe buffers. Allocates whole 4096-byte pages.

#include "types.h"
#include "param.h"
#include "memlayout.h"
#include "spinlock.h"
#include "riscv.h"
#include "defs.h"
#include "stdlib.h"

void freerange(void *pa_start, void *pa_end);

extern char end[]; // first address after kernel.
                   // defined by kernel.ld.

struct run {
  struct run *next;
};

struct {
  struct spinlock lock;
  struct run *freelist;
} kmems[NCPU];

void
kinit()
{
    uint64 pageNum = (((void *)PHYSTOP) - (void *)end) / PGSIZE;
    uint64 cpuPageNum = pageNum / NCPU;

    for (int i = 1; i < NCPU;i++){
        kmems[0].freelist = NULL;
        initlock(&kmems[i].lock, "kmem");
        if(i == NCPU - 1)
            freerange((void *)(end + i * cpuPageNum * PGSIZE), (void *)PHYSTOP);
        else
            freerange((void *)(end + i * cpuPageNum * PGSIZE), (void *)(end + (i + 1) * cpuPageNum * PGSIZE));
        kmems[i].freelist = kmems[0].freelist;
    }
    kmems[0].freelist = NULL;
    freerange(end, (void *)(end + cpuPageNum * PGSIZE));
}

void
freerange(void *pa_start, void *pa_end)
{
    char *p;
    p = (char *)PGROUNDUP((uint64)pa_start);
    for (; p + PGSIZE <= (char *)pa_end && p + PGSIZE <= (char *)PHYSTOP; p += PGSIZE)
        kfree(p);
}

// Free the page of physical memory pointed at by v,
// which normally should have been returned by a
// call to kalloc().  (The exception is when
// initializing the allocator; see kinit above.)
void
kfree(void *pa)
{
    push_off();
    int cpu = cpuid();
    pop_off();

    struct run *r;

    if (((uint64)pa % PGSIZE) != 0 || (char *)pa < end || (uint64)pa >= PHYSTOP)
        panic("kfree");

    // Fill with junk to catch dangling refs.
    memset(pa, 1, PGSIZE);

    r = (struct run *)pa;

    acquire(&kmems[cpu].lock);
    r->next = kmems[cpu].freelist;
    kmems[cpu].freelist = r;
    release(&kmems[cpu].lock);
}

// Allocate one 4096-byte page of physical memory.
// Returns a pointer that the kernel can use.
// Returns 0 if the memory cannot be allocated.
void *
kalloc()
{
  struct run *r;

  push_off();
  int cpu = cpuid();
  pop_off();

  acquire(&kmems[cpu].lock);
  r = kmems[cpu].freelist;
  if(r)
      kmems[cpu].freelist = r->next;
  release(&kmems[cpu].lock);

  if(!r){
      cpu = 0;
      while (cpu < 8 && !r)
      {
          if (!holding(&kmems[cpu].lock) && kmems[cpu].freelist)
          {
              acquire(&kmems[cpu].lock);
              r = kmems[cpu].freelist;
              kmems[cpu].freelist = r->next;
              release(&kmems[cpu].lock);
          }
          cpu++;
      }
  }

//仍然未得到，等待
  if (!r)
  {
      cpu = 0;
      while (cpu < 8 && !r)
      {
          if (kmems[cpu].freelist)
          {
              acquire(&kmems[cpu].lock);
              r = kmems[cpu].freelist;
              kmems[cpu].freelist = r->next;
              release(&kmems[cpu].lock);
          }
          cpu++;
      }
  }

  if(r)
    memset((char*)r, 5, PGSIZE); // fill with junk
  return (void*)r;
}
